<script src="../../../../../../Users/谢光洁/Documents/WeChat Files/wxid_63loj5jtntk652/Files/http.js"></script>
<template>
  <div id="api-interface">
    <v-header title="API服务接口" :saveShow="false" :showDownloadBtn="false"></v-header>
    <div class="main-cont">
      <top-toolbar v-on:operate="handleToolClick" :buttonsObj="buttonsObj"></top-toolbar>
      <el-table :data="tableData.list"
                highlight-current-row
                @current-change="rowClick"
                ref="table"
      >
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="interfaceCode" label="接口编码" show-overflow-tooltip></el-table-column>
        <el-table-column prop="interfaceName" label="接口名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="moduleName" label="所属模块" show-overflow-tooltip></el-table-column>
        <el-table-column prop="interfaceStatus" label="状态" :formatter="transData"></el-table-column>
        <el-table-column prop="transType" label="交易类型" :formatter="transData"></el-table-column>
        <!-- <el-table-column prop="opendIdTranslateFlag" label="openid转换" :formatter="transData"></el-table-column>
        <el-table-column prop="orgJnlIdTranslateFlag" label="流水转换" :formatter="transData"></el-table-column> -->
        <el-table-column prop="onlineTime" label="上线时间" :formatter="transOnlineTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="onlineInterface(scope.row.interfaceId,scope.row)">上线</el-button>
            <el-button type="text" class="mock" size="mini" @click="offlineInterface(scope.row.interfaceId,scope.row)">下线</el-button>
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="scope.row">API Mock</el-dropdown-item>
                <el-dropdown-item :command="{rowData: scope.row, flag: 'apidialog'}">接口调用</el-dropdown-item>
                <el-dropdown-item :command="{flag:''}"><router-link to='APICall' target="div">API调用</router-link></el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="tableData.total">
      </el-pagination>
      <div class="tabs">
        <el-tabs v-model="activeName">
          <!--<el-tab-pane label="设置错误信息" name="first"></el-tab-pane>-->
          <el-tab-pane label="设置接口字段" name="second"></el-tab-pane>
          <el-tab-pane label="修改服务接口" name="third"></el-tab-pane>
          <el-tab-pane label="查看服务接口" name="fourth"></el-tab-pane>
        </el-tabs>
        <keep-alive v-if="aliveShow">
          <component :is="view" :Data="tabsData" :messages="messages" :opts="opts" :moduleIdOpts="moduleData.list"></component>
        </keep-alive>
      </div>
    </div>
    <!-- 新增服务接口dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" @close="addInterfaceCancel" width="900px">
      <el-form :model="interfacePostData" :rules="interfacePostDataRules" ref="interfacePostForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="接口编码" :label-width="formLabelWidth"  prop="interfaceCode">
              <el-input v-model="interfacePostData.interfaceCode" placeholder="请输入接口编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接口名称" :label-width="formLabelWidth"  prop="interfaceName">
              <el-input v-model="interfacePostData.interfaceName" placeholder="请输入接口名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属模块" :label-width="formLabelWidth"  prop="moduleName" :show-message="isModuleErr">
              <a href="javascript:void(0);" class="select" @click="openModuleList('add')">
                <span>{{ interfacePostData.moduleName && interfacePostData.moduleName !== '' ? interfacePostData.moduleName:'请选择所属模块' }}</span>
              </a>
            </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="授权访问模式" :label-width="formLabelWidth"  prop="auditModel">
                <el-select v-model="interfacePostData.auditModel" placeholder="请选择授权访问模式" popper-class="zIndex-popper">
                  <el-option
                          v-for="item in opts.auditModel"
                          :key="item.value"
                          :label="item.name"
                          :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="编码格式" :label-width="formLabelWidth">
              <el-input v-model="interfacePostData.fieldEncoding" placeholder="请输入编码格式"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接口描述信息" :label-width="formLabelWidth"  prop="interfaceDesc">
              <el-input v-model="interfacePostData.interfaceDesc" placeholder="请输入接口描述信息"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="交易类型" :label-width="formLabelWidth"  prop="transType">
              <el-select v-model="interfacePostData.transType" placeholder="请选择交易类型" popper-class="zIndex-popper">
                <el-option
                        v-for="item in opts.transType"
                        :key="item.value"
                        :label="item.name"
                        :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="openid转换标识" :label-width="formLabelWidth"  prop="opendIdTranslateFlag">
              <el-select v-model="interfacePostData.opendIdTranslateFlag" placeholder="请选择openid转换标识" popper-class="zIndex-popper">
                <el-option
                        v-for="item in opts.opendIdTranslateFlag"
                        :key="item.value"
                        :label="item.name"
                        :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="流水转换标识" :label-width="formLabelWidth"  prop="orgJnlIdTranslateFlag">
              <el-select v-model="interfacePostData.orgJnlIdTranslateFlag" placeholder="请选择流水转换标识" popper-class="zIndex-popper">
                <el-option
                        v-for="item in opts.orgJnlIdTranslateFlag"
                        :key="item.value"
                        :label="item.name"
                        :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!--<el-col :span="12">-->
            <!--<el-form-item label="是否鉴权" :label-width="formLabelWidth">-->
              <!--<el-switch v-model="interfacePostData.isAuthorized"-->
                         <!--active-text="开"-->
                         <!--inactive-text="关">-->
              <!--</el-switch>-->
            <!--</el-form-item>-->
          <!--</el-col>-->
        </el-row>
        <el-form-item class="dialogbtn">
          <el-button @click="addInterfaceReset()">重置</el-button>
          <el-button @click="addInterfaceCancel()">关闭</el-button>
          <el-button type="primary" @click="addInterfaceSubmit()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查询服务接口dialog -->
    <el-dialog :title="queryDialogTitle" :visible.sync="queryDialogVisible" @close="queryDialogClose" width="900px">
      <el-form v-model="queryData">
        <el-row>
          <el-col :span="12">
            <el-form-item label="接口名称" :label-width="formLabelWidth">
              <el-input v-model="queryData.interfaceName" placeholder="请输入接口名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属模块" :label-width="formLabelWidth"  prop="moduleName" :show-message="isModuleErr">
              <a href="javascript:void(0);" class="select" @click="openModuleList('search')">
                <span>{{ queryData.moduleName && queryData.moduleName !== '' ? queryData.moduleName:'请选择所属模块' }}</span>
              </a>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" :label-width="formLabelWidth">
            <el-select v-model="queryData.interfaceStatus" placeholder="请选择接口状态" popper-class="zIndex-popper">
              <el-option
                v-for="item in opts.interfaceStatus"
                :key="item.value"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="dialogbtn">
          <el-button @click="queryApiInterfaceReset()">重置</el-button>
          <el-button @click="queryDialogClose()">关闭</el-button>
          <el-button type="primary" @click="queryInterfaceSubmit()">查询</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 模拟（MOCK）数据开关 -->
    <el-dialog :title="mockDialogTitle" :visible.sync="mockDialogVisible"  width="900px" class="mock" @close="mockDialogClose">
      <el-form :model="mockForm" :rules="mockFormRules" ref="mockForm" label-width="110px" class="demo-ruleForm">
        <el-form-item label="API Mock：">
          <el-switch v-model="mockForm.switch"
                     active-text="开"
                     inactive-text="关"></el-switch>
        </el-form-item>
        <el-form-item label="Mock数据：" prop="mockData" v-if="isMockOpen">
          <el-input type="textarea" rows="10" v-model="mockForm.mockData"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="submitMockForm">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 接口调用弹框 -->
    <el-dialog title="" :visible.sync="apiUseDiaIsShow" width="600px" class="apidiglog">
      <div class="Platform">
        <div class="PlatformTitle">Platform:</div>
        <div class="PlatformRt">
          <el-radio-group v-model="radioJsonValue" @change="radioJsonTypeClick">
            <el-radio :label="1">JS</el-radio>
            <el-radio :label="2">IOS</el-radio>
            <el-radio :label="3">Android</el-radio>
          </el-radio-group>
        </div>
      </div>
      <el-input type="textarea" :rows="15" :value="apiText"></el-input>
        <el-row class="toolButton">
          <el-button size="mini" @click="copyDataFn">复制</el-button>
          <el-button size="mini" @click="apiUseDiaIsShow=false">关闭</el-button>
        </el-row>
    </el-dialog>
    <!-- 选择模块列表弹窗 -->
    <v-select
      title="模块列表"
      :isShow="moduleListDialogVisible"
      :dataObj="moduleData"
      :tableLabels="tableLabels"
      @close="closeDialog"
      @page-changes="handlePageChanges"
      @select-data="selectModule"></v-select>
  </div>
</template>

<script type="text/ecmascript-6">
  import {VHeader} from '../../../../components'
  import TopToolbar from '../../../../components/TopToolbar/TopToolbar'
  import setErrMsg from './com/setErrMsg.vue'
  import setfieldData from './com/setfieldData.vue'
  import modifyInterface from './com/modifyInterface.vue'
  import toDetail from './com/toDetail.vue'
  import VSelect from '../../../comm/vSelect.vue'
  import ajax from '../../../../api/ajax/ajax'
  import api from '../../../../api/url'
  export default {
    name: 'a-p-i-module',
    components: {
      VHeader: VHeader,
      TopToolbar: TopToolbar,
      // 设置错误代码
      setErrMsg: setErrMsg,
      setfieldData: setfieldData,
      modifyInterface: modifyInterface,
      toDetail: toDetail,
      VSelect: VSelect
    },
    watch: {
      activeName (val) {
        switch (val) {
//          case 'first':
//            this.view = setErrMsg
//            break
          case 'second':
            this.view = setfieldData
            break
          case 'third':
            this.view = modifyInterface
            break
          case 'fourth':
            this.view = toDetail
            break
        }
      },
      'mockForm.switch' (val) {
        this.isMockOpen = val
      }
    },
    data () {
      return {
        APIMockTypeVal: '',
        radioJsonValue: 1, // 接口调用mock数据显示类型 1为Android 2 IOS 3 JS
        buttonsObj: [
          {
            text: '新增',
            oprType: 'addInterface'
          },
          {
            text: '查询',
            oprType: 'queryInterface'
          }
        ],
        // 当前查询条件
        ifQueryReset: false,
        queryDataCache: {},
        queryData: {
          interfaceName: null,
          interfaceStatus: null,
          moduleId: null
        },
        // tabs
        activeName: 'second',
        // tabs view
        view: 'setfieldData',
        // tabs data
        aliveShow: false,
        apiUseDiaIsShow: false,
        tabsData: '',
        tableData: '',
        moduleData: {},
        // 新增服务接口
        dialogTitle: '',
        dialogVisible: false,
        // 查询服务接口
        queryDialogTitle: '',
        queryDialogVisible: false,
        mockDialogVisible: false,
        mockDialogTitle: 'Mock配置：',
        mockForm: {
          switch: false,
          mockData: '{"name":"周先杰","age":25}',
          interfaceId: ''
        },
        mockFormRules: {
          mockData: [
            { required: true, message: '请填写mock数据', trigger: 'blur' }
          ]
        },
        formLabelWidth: '140px',
        interfacePostDataRules: {
          interfaceCode: [
            {required: true, trigger: 'blur', message: '接口编码不能为空'}
          ],
          interfaceName: [
            {required: true, trigger: 'blur', message: '接口名称不能为空'}
          ],
          // 所属模块
          moduleName: [
            {required: true, message: '请选择所属模块', trigger: 'change'}
          ],
          // 授权访问模式
          auditModel: [
            {required: true, trigger: 'change', message: '请选择授权访问模式'}
          ],
          // 接口描述信息
          interfaceDesc: [
            {required: true, trigger: 'blur', message: '接口描述信息不能为空'}
          ],
          // 交易类型
          transType: [
            {required: true, trigger: 'change', message: '请选择交易类型'}
          ],
          // openid转换标识
          opendIdTranslateFlag: [
            {required: true, trigger: 'change', message: '请选择openid转换标识'}
          ],
          // 流水转换标识
          orgJnlIdTranslateFlag: [
            {required: true, trigger: 'change', message: '请选择流水转换标识'}
          ]
        },
        interfacePostData: {
          sourceType: '00',
          fieldEncoding: 'UTF-8',
          isAuthorized: false
        },
        opts: {
            auditModel: [
                {name: '按模块开放', value: '00'},
                {name: '单独申请开放', value: '01'}
            ],
            transType: [
//                {name: '原子交易', value: '0'},
                {name: '聚合系统', value: '1'}
//                {name: '接入系统', value: '2'}
            ],
            opendIdTranslateFlag: [
                {name: '不转换', value: '0'}
//                {name: '转换', value: '1'}
            ],
            orgJnlIdTranslateFlag: [
                {name: '不转换', value: '0'}
//                {name: '转换', value: '1'}
            ],
          interfaceStatus: [
            {name: '待开放', value: '00'},
            {name: '已开放', value: '01'},
            {name: '已下线', value: '02'}
          ]
        },
        // 服务模块状态
        messages: {
          auditModel: {
            '00': '按模块开放',
            '01': '单独申请开放'
          },
          interfaceStatus: {
            '00': '待开放',
            '01': '已开放',
            '02': '已下线'
          },
          transType: {
            '0': '原子交易',
            '1': '聚合系统',
            '2': '接入系统'
          },
          opendIdTranslateFlag: {
            '0': '不转换',
            '1': '转换'
          },
          orgJnlIdTranslateFlag: {
            '0': '不转换',
            '1': '转换'
          }
        },
        // 分页数据
        currentPage: 1,
        pageSize: 10,
        // 模块列表弹框数据
        moduleListOpenType: '',
        moduleListDialogVisible: false,
        moduleListCurrentPage: 1,
        isModuleErr: false,
        tableLabels: {
          moduleName: '模块名称',
          moduleCode: '模块代码',
          createTime: '创建时间'
        },
        apiText: ''
      }
    },
    methods: {
      radioJsonTypeClick (val) {
        switch (val) {
          case 1:
            this.apiText = `$.ajax({
            type: "post",
            contentType: "application/json",
            dataType: "json",
            url: "http://localhost:8080/service.action",
            data: {"interface": "${this.APIMockTypeVal}"},
            async: true,
            success:function(res) {
              console.log(res.msg);
            }
          })`
            break
          case 2:
            this.apiText = `NSMutableDictionary *headDic = [NSMutableDictionary dictionary];
    [headDic setValue:@"application/json" forKey:@"Content-Type"];

    NSMutableString * postPramstr = [NSMutableString string];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:"${this.APIMockTypeVal}" forKey:@"interface"];
    if (parameters) {
        for (NSString * key in [parameters allKeys]) {
            //[request setValue:headDic[key] forHTTPHeaderField:key];
            [postPramstr appendString:key];
            [postPramstr appendString:@"="];
            [postPramstr appendString:parameters[key]];
            [postPramstr appendString:@"&"];
        }
    }
    postPramstr = [[postPramstr substringToIndex:[postPramstr length]-1] mutableCopy];
    NSString * URLString =@"http://localhost:8080/service.action";
    NSURL * URL = [NSURL URLWithString:URLString];
    NSString * postString = postPramstr;
    NSData * postData = [postString dataUsingEncoding:NSUTF8StringEncoding];  //将请求参数字符串转成NSData类型
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc]init];
    [request setHTTPMethod:@"POST"]; //指定请求方式
    [request setURL:URL]; //设置请求的地址
    [request setHTTPBody:postData];  //设置请求的参数
    [request setTimeoutInterval:30];
    [request setCachePolicy:1];
    if (headDic) {
        for (NSString * key in [headDic allKeys]) {
            [request setValue:headDic[key] forHTTPHeaderField:key];
        }
    }
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_semaphore_signal(semaphore);
    }];
    [task resume];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);`
            break
          case 3:
            this.apiText = `public  static  Map  getHead(){
              Map<String,String> params=new HashMap<>();
                      params.put("interface","${this.APIMockTypeVal}");
                      params.put("sequenceid",System.currentTimeMillis()+"");
                      StringBuffer stringBuffer = new StringBuffer();        //存储封装好的请求体信息
                      try {
                          for(Map.Entry<String, String> entry : params.entrySet()) {
                              stringBuffer.append(entry.getKey())
                                      .append("=")
                                      .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                                      .append("&");
                          }
                          stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //删除最后的一个"&"
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                      URL url = null;
                      try {
                          url = new URL("http://localhost:8080/service.action");
                          HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                          httpURLConnection.setRequestMethod("POST");// 提交模式
                          httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
                          httpURLConnection.setReadTimeout(2000);//读取超时 单位毫秒
                          httpURLConnection.setRequestProperty("contentType","application/json");
                          // 发送POST请求必须设置如下两行
                          httpURLConnection.setDoOutput(true);
                          httpURLConnection.setDoInput(true);
                          // 获取URLConnection对象对应的输出流
                          PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
                          // 发送请求参数
                          printWriter.write(stringBuffer.toString());//post的参数 xx=xx&yy=yy
                          // flush输出流的缓冲
                          printWriter.flush();
                          //开始获取数据
                          BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
                          ByteArrayOutputStream bos = new ByteArrayOutputStream();
                          int len;
                          byte[] arr = new byte[1024];
                          while((len=bis.read(arr))!= -1){
                              bos.write(arr,0,len);
                              bos.flush();
                          }
                          bos.close();
                          bos.toString("utf-8");
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
            }`
            break
        }
      },
      // 工具栏操作
      handleToolClick (opt) {
        switch (opt) {
          case 'addInterface':
            this.addInterface()
            break
          case 'queryInterface':
            this.queryInterface()
            break
          default:
            break
        }
      },
      // 分页触发事件
      handleCurrentChange (e) {
        this.currentPage = e
        this.initializeData(e, this.pageSize)
      },
      handleSizeChange (e) {
        this.currentPage = 1
        this.initializeData(this.currentPage, e)
      },
      // 列表查询
      initializeData (e = 1, s = 10) {
        ajax.post(api.LISTAPIINTERFACE + '?pageNum=' + e + '&pageSize=' + s, this.queryDataCache, true).then(res => {
          this.tableData = res
          this.$refs.table.setCurrentRow(this.tableData.list[0])
        }).catch(res => {})
        ajax.post(api.LISTAPIMODULE, {pageNum: '1', pageSize: '20'}).then(res => {
            this.moduleData = res
        }).catch(res => {
          this.$message({
            showClose: true,
            message: res.errorMsg,
            type: 'warning'
          })
        })
      },
      // 格式化数据
      transData (row, column, cellValue, index) {
        let targetData = row[column.property]
        if (targetData) {
          return this.messages[column.property][row[column.property]]
        }
      },
      // 上线时间
      transOnlineTime (row, column) {
        let time = row[column.property]
        if (time) {
          return this.transTime(time, 't')
        }
      },
      // 时间戳 => 时间 XXXX-XX-XX XX:XX:XX
      transTime (e, format) {
        switch (format) {
          case 't':
            let date = new Date(e)
            let moth = (date.getMonth() < 10) ? ('0' + (date.getMonth() + 1)) : date.getMonth()
            let day = (date.getDate() < 10) ? ('0' + date.getDate()) : date.getDate()
            let hours = (date.getHours() < 10) ? ('0' + date.getHours()) : date.getHours()
            let minutes = (date.getMinutes() < 10) ? ('0' + date.getMinutes()) : date.getMinutes()
            let seconds = (date.getSeconds() < 10) ? ('0' + date.getSeconds()) : date.getSeconds()
            return `${date.getFullYear()}-${moth}-${day}  ${hours}:${minutes}:${seconds}`
        }
      },
      // interfacePostData重置
      interfaceDataReset () {
        this.$refs['interfacePostForm'].resetFields()
        this.interfacePostData = {
          sourceType: '00',
          fieldEncoding: 'UTF-8'
        }
      },
      // 格式化数据结束
      // 新增服务接口
      addInterface () {
        this.dialogTitle = '新增服务接口'
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs['interfacePostForm'].clearValidate()
        })
      },
      addInterfaceSubmit () {
        // 校验
        this.$refs.interfacePostForm.validate((valid, errFields) => {
          if (valid) {
            // 编码格式默认为UTF-8
            if (!this.interfacePostData.fieldEncoding) {
              this.interfacePostData.fieldEncoding = 'UTF-8'
            }
            this.interfacePostData.isAuthorized = this.interfacePostData.isAuthorized ? '1' : '0'
            ajax.post(api.ADDAPIINTERFACE, this.interfacePostData, true).then(res => {
              if (res === 'success') {
                this.$message({
                  message: '新建服务接口成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.dialogTitle = ''
                this.interfaceDataReset()
                this.currentPage = 1
                this.initializeData()
              }
            }).catch(res => {
              this.$message({
                showClose: true,
                message: res.errorMsg,
                type: 'warning'
              })
            })
          } else {
            if (errFields['moduleName']) {
              if (this.interfacePostData.moduleName === undefined ||
              this.interfacePostData.moduleName === '') {
                this.isModuleErr = true
              }
            }
            return false
          }
        })
      },
      addInterfaceCancel () {
        this.dialogVisible = false
        this.dialogTitle = ''
        this.isModuleErr = false
        this.interfaceDataReset()
        this.$refs['interfacePostForm'].resetFields()
      },
      addInterfaceReset () {
        this.interfaceDataReset()
      },
      // 查询服务接口
      queryInterface () {
        this.queryDialogTitle = '查询服务接口'
        this.queryDialogVisible = true
        this.ifQueryReset = true
      },
      queryDialogClose () {
        // 不缓存查询的值
        this.queryData = {}
        this.queryDialogVisible = false
        this.isModuleErr = false
      },
      queryApiInterfaceReset () {
        this.queryData.interfaceName = null
        this.queryData.interfaceStatus = null
        this.queryData.moduleId = null
      },
      queryInterfaceSubmit () {
        this.ifQueryReset = false
        if (!this.queryData.interfaceName) {
          this.queryData.interfaceName = null
        }
        this.queryDataCache.moduleId = this.queryData.moduleId
        this.queryDataCache.interfaceName = this.queryData.interfaceName
        this.queryDataCache.interfaceStatus = this.queryData.interfaceStatus
          this.currentPage = 1
          this.initializeData()
        this.queryDialogVisible = false
        this.queryDialogTitle = ''
      },
      // 列表 选中事件,获取tabs数据
      rowClick (row, oldrow) {
        if (row) {
          this.aliveShow = true
        } else {
          this.aliveShow = false
        }
        this.tabsData = row
        if (this.activeName === '0') {
          this.activeName = 'second'
        }
      },
      // 服务接口上线
      onlineInterface (id, row) {
        ajax.post(api.ONLINEAPIINTERFACE, {interfaceId: id}, true).then(res => {
          if (res === 'success') {
            this.$message({
              message: '上线成功',
              type: 'success'
            })
            row.interfaceStatus = '01'
            // this.initializeData()
          }
        }).catch(res => {
          this.$message({
            showClose: true,
            message: res.errorMsg,
            type: 'warning'
          })
        })
      },
      // 服务接口下线
      offlineInterface (id, row) {
        ajax.post(api.OFFLINEAPIINTERFACE, {interfaceId: id}, true).then(res => {
          if (res === 'success') {
            this.$message({
              message: '下线成功',
              type: 'success'
            })
            // alert(status)
            row.interfaceStatus = '02'
            // this.initializeData()
          }
        }).catch(res => {
          this.$message({
            showClose: true,
            message: res.errorMsg,
            type: 'warning'
          })
        })
      },
      // 便捷API Mock 数据
      handleCommand (rowData) {
          if (rowData.flag === '') {
              return
          }
        if (rowData.flag !== 'apidialog') {
          this.mockDialogTitle = 'Mock配置：' + rowData.interfaceCode
          this.mockForm.interfaceId = rowData.interfaceId
          if (rowData.isMock !== '0' && rowData.isMock !== null) {
            this.mockForm.switch = true // 开关选项
          }
          // 取到后台字符串数据进行格式化显示
          let jsonStr = rowData.textMock ? JSON.stringify(JSON.parse(rowData.textMock), null, '  ') : ''
          this.mockForm.mockData = jsonStr // 打开时 显示mock数据
          this.mockDialogVisible = true
        } else {
          if (rowData.flag === 'apidialog') {
            this.APIMockTypeVal = rowData.rowData.interfaceCode
            this.apiText = `$.ajax({
  type: "post",
  contentType: "application/json",
  dataType: "json",
  url: "http://localhost:8080/service.action",
  data: {"interface": "${rowData.rowData.interfaceCode}"},
  async: true,
  success:function(res) {
    console.log(res.msg);
  }
})`
            this.apiUseDiaIsShow = true
          }
        }
      },
      mockDialogClose () {
        this.mockForm.switch = false // 开关选项
        this.$refs['mockForm'].resetFields()
      },
      isJsonString (str) {
          try {
              JSON.parse(str)
          } catch (e) {
              return false
          }
          return true
      },
      // 复制功能
      copyDataFn () {
        this.$copyText(this.apiText).then(e => {
          this.$message({
            message: '复制成功',
            type: 'success'
          }, e => {
            this.$message({
              message: '复制成功',
              type: 'error'
            })
          })
        })
      },
      // 更行mock 数据接口
      upDataMOck () {
        let params = {
          mockText: this.mockForm.mockData, // 实际mock 数据
          isMock: this.mockForm.switch ? 1 : 0, // mock 开关 0：关闭 1：打开
          interfaceId: this.mockForm.interfaceId // 接口ID
        }
        ajax.postFormData(api.UPDATEMOCKINFO, params, true).then(res => {
          this.$message({
            type: 'success',
            message: 'mock数据设置成功！'
          })
          this.currentPage = 1
          this.initializeData()
          this.mockDialogVisible = false
        }).catch(res => {
          this.$message({
            showClose: true,
            message: res.errorMsg,
            type: 'warning'
          })
        })
      },
      // mock 提交
      submitMockForm () {
        this.$refs['mockForm'].validate((valid) => {
          if (valid) {
            // JSON字符串转JSON对象 校验JSON格式
            let bool = this.isJsonString(this.mockForm.mockData)
            // 如果JSON格式正确
            if (bool) {
              // JSON字符串转对象后判断是否是空对象
              let a = JSON.parse(this.mockForm.mockData)
              // es6方法判断
              if (Object.keys(a).length === 0) {
                this.$message({
                  type: 'warning',
                  message: '不能为空对象'
                })
              } else {
                // 输入JOSN正确且不是空对象则
                this.upDataMOck()
              }
            } else {
              // JSON格式不正确
              this.$alert('示例：{ "key: "value", "key": [ ] }', '失败！请检查Josn格式是否正确')
            }
          }
        })
      },
      // 选择模块列表
      openModuleList (t) {
        this.moduleListOpenType = t
        this.moduleListDialogVisible = true
      },
      selectModule (data) {
        if (this.moduleListOpenType === 'search') {
          this.queryData.moduleId = data.moduleId
          this.queryData.moduleName = data.moduleName
        } else if (this.moduleListOpenType === 'add') {
          this.interfacePostData.moduleId = data.moduleId
          this.interfacePostData.moduleName = data.moduleName
          if (this.interfacePostData.moduleName !== '') {
            this.isModuleErr = false
          }
        }
        this.moduleListDialogVisible = false
      },
      handleModuleListChange (p) {
        this.moduleListCurrentPage = p
        ajax.post(api.LISTAPIMODULE + '?pageSize=10&pageNum=' + p, {}).then(res => {
          this.moduleData = res
        }).catch(res => {
          this.$message({
            showClose: true,
            message: res.errorMsg,
            type: 'warning'
          })
        })
      },
      // 关闭选择模块列表弹窗
      closeDialog () {
        this.moduleListDialogVisible = false
      },
      // 处理模块列表分页
      handlePageChanges (params) {
        this.handleModuleListChange(params.currentPage)
      }
    },
    mounted () {
      this.initializeData()
    },
    created () {
      this.isMockOpen = false
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  #api-interface
    height 100%
    .main-cont
      padding:10px
      height calc(100% - 56px)
      overflow auto
      overflow-x hidden
    .el-table
      margin-top:10px
      width: 100%
      padding-left:10px
    .el-dialog
      .el-col
        padding:0 12px
      .el-pagination
        padding-top:20px
      .el-select
        display:block
        margin:0
      .dialogbtn
        text-align:right
    .el-dropdown-link
      color #016dfb
      font-size 12px
    .cell .el-button + .el-button.mock
      margin-left 0 !important
      padding 0 3px
      border-left 1px solid #ddd
      border-right 1px solid #ddd
    .select
      display block
      width 100%
      padding 0 15px
      height 40px
      line-height 40px
      border 1px solid #dcdfe6
      border-radius 4px
      background #f5f5f5
      box-sizing border-box
    .apidiglog
      .el-row
        margin-top 15px !important
        text-align right !important
    .Platform
       height 60px
       line-height 60px
      .PlatformTitle
        margin-right 20px
        float left
      .PlatformRt
        float left
</style>
